package com.cc.demo2;

import com.cc.mapper.GoodMapper;
import com.dy.cc.Good;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

//给索引库中添加文档（添加数据） 先构建mapping ===> put/good/_doc/1
public class AddClient {
    @Autowired
    private GoodMapper goodMapper;
    public static void main(String[] args) throws IOException {
        //创建java和es的链接
        HttpHost httpHost = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        System.out.println(client.indices());

        //指令方式: put /good/_doc/1 {}
        IndexRequest indexRequest = new IndexRequest();
        // 创建IndexRequest并指定类型
        //IndexRequest indexRequest = new IndexRequest("your_index_name", "your_type_name");
        indexRequest.index("good").id("2");
        Good good = new Good();

        good.setName("华为mate40");
        good.setPrice(9999);
        good.setImg("https://spyx-12x.oss-cn-shanghai.aliyuncs.com/2024/11/18/380912f8a7d24c7985e05730764092c04.jpg");



        // 将Java对象转换成JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String jsongood = mapper.writeValueAsString(good);

        // 设置源数据和内容类型
        indexRequest.source(jsongood, XContentType.JSON);

        // 发送请求，添加数据
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println("添加数据的结果：" + response.getIndex());

        //关闭连接
        client.close();
    }
}
